<template>
  <div class="leftMenu">
    <Menu :active-name="name"
          theme="dark"
          width="auto"
          :open-names="['1']">
      <template v-for="(item, index) in list">
        <Submenu :name="item.mid"
                 :key="index"
                 v-if="item.childen.length !==0">
          <template slot="title">
            <Icon :type="item.icon" />
            {{ item.name }}
          </template>
          <MenuItem :name="item2.mid"
                    v-for="(item2, index) in item.childen"
                    :key="index"
                    @click.native="goPath(item2)">{{ item2.name }}</MenuItem>
        </Submenu>

        <MenuItem :name="item.mid"
                  @click.native="goPath(item)"
                  v-if="item.childen.length ===0"
                  :key="index">
        <Icon :type="item.icon" />
        {{ item.name }}
        </MenuItem>

      </template>

    </Menu>
  </div>
</template>

<script>
import { getMenu } from 'server/admin_k.js'
export default {
  data() {
    return {
      list: [],
      allList: [],
      name: -1,
  
    }
  },
  created() {
    // 开始监听登录是否请求完毕
    this.$show.$on('isLogin', this.test)
  },
  methods: {
    _getMenu() {
      getMenu().then(res => {
        let list = res.data.filter(v => v.fid === 0)

        this.allList = res.data
        list.forEach(v => {
          v.childen = []
          res.data.forEach(v2 => {
            if (v2.fid == v.mid) {
              v.childen.push(v2)
            }
          })
        })
        this.list = list
        this.checkName()
      })
    },
    goPath(item) {
      const res = this.checkPower(item.mid)

      if (res && item.path !== this.$route.path) {
        
        this.$emit('changeMenu',{
          name:item.name
        })
        this.$router.push(item.path)
      }
    },
    changeIndex(path) {
      const index = this.allList.findIndex(v => v.path == path)
      const mid = index === -1 ? -1 : this.allList[index].mid
      const res = this.checkPower(mid)
    },
    // 确认是否存在权限
    checkPower(mid, isAdmin = false) {
      const mids = this.$store.state.staff.mids

      const index = mids.findIndex(v => v == mid)
      if (index === -1 && !isAdmin) {
        this.$Message.warning(
          '抱歉，您没有权限访问此菜单，如果想获得授权请联系作者！'
        )
        return false
      }
      return true
    },
    checkName() {
      let path = this.$route.path
      let mid = -1
      this.allList.forEach(v => {
        if (v.path == path) {
          mid = v.mid
        }
      })
      this.name = mid
      let res = this.checkPower(mid, true)
      if (!res && path !== '/admin') {
        this.$router.replace('/admin')
      }
    },
    test() {
      this._getMenu()
    }
  },

  watch: {
    // 监听路由跳转
    $route(to, from) {
      this.changeIndex(to.path)
    }
  }
}
</script>

<style scoped>
.leftMenu {
  /* overflow-y: scroll; */
}
</style>
